package io.xxx.omni.oss.sdk

import com.google.gson.JsonObject
import io.xxx.omni.oss.common.toJsonObject
import io.xxx.omni.oss.common.toJsonString
import io.xxx.omni.oss.domain.Store
import okhttp3.Call
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.apache.commons.codec.digest.DigestUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import org.springframework.web.util.UriComponentsBuilder
import java.util.*

@Component
class AkcClient {

    @Autowired
    private lateinit var client: OkHttpClient

    private val httpUrl = "https://openapi.aikucun.com/route/rest"

    fun execute(store: Store, interfaceName: String, request: Map<String, Any>): JsonObject {
        val authorization = store.authorization
        val signMap = TreeMap<String, Any>()
        signMap["appid"] = authorization["appid"]
        signMap["noncestr"] = "Winner-ERP"
        signMap["timestamp"] = System.currentTimeMillis() / 1000
        signMap["version"] = "1.0"
        signMap["format"] = "json"
        signMap["interfaceName"] = interfaceName
        val urlBuilder = UriComponentsBuilder
            .fromHttpUrl(httpUrl)
        signMap.forEach { urlBuilder.queryParam(it.key, it.value) }
        signMap["appsecret"] = authorization["appsecret"]
        val jsonString = request.toJsonString()
        signMap["body"] = jsonString
        val sign = DigestUtils.sha1Hex(signMap.entries.joinToString("&"))
        urlBuilder.queryParam("sign", sign)
        val url = urlBuilder.build(false).toUriString()
        val requestBody = jsonString.toRequestBody("application/json".toMediaType())
        val call: Call = client.newCall(
            Request.Builder()
                .url(url)
                .post(requestBody)
                .build()
        )
        val response = call.execute()
        return response.body!!.string().toJsonObject()
    }
}